# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：deal_concurrent.py
#日期：2019-11-19
#备注：并发编程的多种场景：多线程threading、异步asyncio、多进程multiprocessing、协程gevent
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import time
import threading
import asyncio
import multiprocessing
from gevent import monkey; monkey.patch_all()
import gevent

'''''''''''''''''''''''''''
func--> 具体业务函数
t --> int类型
'''''''''''''''''''''''''''

# 多线程threading
def thread_task(func,t):
    sTime = time.time()
    threads = [threading.Thread(target=func, args=(t,)) for t in range(1, t+1)]
    for t in threads:
        t.start()

    for t in threads:
        t.join()

    eTime = time.time()
    s = eTime - sTime
    print('多线程threading花费的时间为：%.2f秒' % (s))


# 异步asyncio
def asyncio_task(func,a):
    sTime = time.time()
    loop = asyncio.get_event_loop()                      # 建立 looptasks
    loop.run_until_complete(asyncio_get(loop,func,a))    # 执行 loop
    loop.close()                                         # 关闭 loop
    eTime = time.time()
    s = eTime - sTime
    print('异步asyncio花费的时间为：%.2f秒' % (s))
async def asyncio_get(loop,func,a):
    tasks = [loop.create_task(func(a)) for a in a]
    await asyncio.wait(tasks)

# 多进程multiprocessing
def process_task(func,p):
    sTime = time.time()
    processes = [multiprocessing.Process(target=func, args=(p,)) for p in range(1, p+1)]
    for p in processes:
        p.start()

    for p in processes:
        p.join()

    eTime = time.time()
    s = eTime - sTime
    print('多进程multiprocessing花费的时间为：%.2f秒' % (s))


# 协程gevent，一个线程：from gevent import monkey; monkey.patch_all()  速度提升
def gevent_task(func,g):
    sTime = time.time()
    run_gevent_list = [gevent.spawn(func,g) for g in g]
    gevent.joinall(run_gevent_list)
    eTime = time.time()
    s = eTime - sTime
    print('协程gevent花费的时间为：%.2f秒' % (s))
